<template>
  <div>
    <el-dialog
      :title="user.isAdd?'商品管理添加':'商品管理修改'"
      :visible.sync="user.isshow"
      @opened="opened"
      @closed="closed"
      @close="close"
    >
      {{form}}
      <el-form :model="form">
        <el-form-item label="一级分类" label-width="120px">
          <el-select v-model="form.first_cateid" placeholder="请选择" @change="firstIdChange">
            <el-option
              v-for="item in catelist"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" label-width="120px">
          <el-select v-model="form.second_cateid" placeholder="请选择">
            <el-option
              v-for="item in seondCateId"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" label-width="120px">
          <el-input v-model="form.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" label-width="120px">
          <el-input v-model="form.market_price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="图片" label-width="120px">
          <up-load @sendFile="sendFile" ref="image"></up-load>
        </el-form-item>

        <el-form-item label="商品规格" label-width="120px">
          <el-select v-model="form.specsid" placeholder="请选择" @change="changeSpces">
            <el-option
              v-for="item in specslist"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性" label-width="120px">
          <el-select v-model="form.specsattr" multiple placeholder="请选择">
            <el-option v-for="item in specsattrs.attrs" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否新品" label-width="120px">
          <el-radio v-model="form.isnew" :label="1">是</el-radio>
          <el-radio v-model="form.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" label-width="120px">
          <el-radio v-model="form.ishot" :label="1">是</el-radio>
          <el-radio v-model="form.ishot" :label="2">否</el-radio>
        </el-form-item>

        <el-form-item label="状态" label-width="120px">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item label="商品描述" label-width="120px">
          <!-- 二、富文本编辑器  添加了条件渲染-->
          <div id="editor" v-if="user.isshow"></div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button v-if="user.isAdd" @click="add">添加</el-button>
        <el-button type="primary" v-else @click="edit">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import E from "wangeditor";
import { mapGetters, mapActions } from "vuex";
import {
  reqgoodsedit,
  reqcatelist,
  reqgoodsinfo,
  reqgoodsadd,
} from "../../../request/api";
import { successAlert, errorAlert } from "../../../utils/alert";
export default {
  props: ["user"],
  mounted() {
    if (this.catelist.length === 0) {
      this.reqCateList();
    }
    // 保证请求回来的是所有的规格
    this.reqSpecsList(true);
  },

  data() {
    return {
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        description: "",
        img: null,
        specsid: "",
        specsattr: [],
        isnew: 1,
        ishot: 1,
        status: 2,
      },
      // list: [],
      // imgUrl: "",
      seondCateId: [],
      specsattrs: [],
    };
  },
  computed: {
    ...mapGetters({
      catelist: "shopCate/list",
      specslist: "shopSpecs/list",
    }),
  },
  methods: {
    ...mapActions({
      reqCateList: "shopCate/reqList",
      reqSpecsList: "shopSpecs/reqLists",
      reqgoodsList: "goods/reqList",
      reqCount: "goods/reqCount",
    }),
    // 验证函数
    checkEmpty() {
      return new Promise((resolve, rejext) => {
        if (this.form.first_cateid == "") {
          errorAlert("一级分类不能为空");
          return;
        }
        if (this.form.second_cateid == "") {
          errorAlert("二级分类不能为空");
          return;
        }
        if (this.form.goodsname == "") {
          errorAlert("商品名称不能为空");
          return;
        }
        if (this.form.price == "") {
          errorAlert("价格不能为空");
          return;
        }
        if (this.form.market_price == "") {
          errorAlert("市场价格不能为空");
          return;
        }
        if (!this.form.img) {
          errorAlert("图片不能为空");
          return;
        }
        if (this.form.specsid == "") {
          errorAlert("规格不能为空");
          return;
        }
        if (this.form.specsattr.length == 0) {
          errorAlert("规格属性不能为空");
          return;
        }
        if (this.editor.txt.html() === "") {
          errorAlert("描述不能空");
          return;
        }
        resolve();
      });
    },

    //一、创建编辑器
    opened() {
      //创建一个编辑器
      this.editor = new E("#editor");
      this.editor.create();
      //给编辑器赋值
      this.editor.txt.html(this.form.description);
    },

    // 选取规格的时候需要拿到的数据
    changeSpces() {
      // 改变规格的时候需要将属性清空
      this.form.specsattr = [];
      this.getAttr();
    },
    // 获取规格的属性
    getAttr() {
      let objAttrs = this.specslist.find(
        (item) => item.id == this.form.specsid
      );
      this.specsattrs = objAttrs ? objAttrs : [];
    },

    // 一级菜单改变的时候
    firstIdChange() {
      // 传的参数不一样不能直接用仓库的方法
      this.form.second_cateid = "";
      this.getSecondCateId();
    },
    // 获取二级菜单
    getSecondCateId() {
      reqcatelist({
        pid: this.form.first_cateid,
      }).then((res) => {
        if (res.data.code == 200) {
          this.seondCateId = res.data.list;
        }
      });
    },

    // 图片
    sendFile(file) {
      this.form.img = file;
    },

    //   关闭是否清空form
    closed() {
      if (!this.user.isAdd) {
        this.empty();
        this.imgUrl = "";
        // this.editor.txt.html(this.form.description);
        // console.log(this.editor.txt.html());
        // this.form.description = this.editor.txt.html();
      }
    },

    close() {
      this.imgUrl = "";
      this.form.description = this.editor.txt.html();
    },
    //修改
    edit() {
      reqgoodsedit({
        ...this.form,
        specsattr: this.form.specsattr.join(","),
        description: this.editor.txt.html(),
      }).then((res) => {
        if (res.data.code == 200) {
          successAlert(res.data.msg);
          //   取消form
          this.cancel();
          //   重新刷新数据
          this.reqgoodsList();
          //   修改后清空form
          this.empty();
        }
      });
    },

    //获取一条数据
    getOne(id) {
      reqgoodsinfo({
        id: id,
      }).then((res) => {
        if (res.data.code == 200) {
          this.form = res.data.list;
          this.form.id = id;
          // 获取二级列表
          this.getSecondCateId();
          // 获取图片信息
          this.$refs.image.imgUrl = this.$pre + this.form.img;

          // console.log(this.form.specsattr);
          // 修改规格属性   返回的是字符串
          this.form.specsattr = this.form.specsattr.split(",");
          // j计算属性列表
          this.getAttr();

          if (!!this.editor) {
            this.editor.txt.html(this.form.description);
          }
        }
      });
    },

    //   取消后form消失
    cancel() {
      this.user.isshow = false;
    },

    // 点击添加后
    add() {
      // 验证是否为空
      this.checkEmpty().then(() => {
        reqgoodsadd({
          ...this.form,
          specsattr: this.form.specsattr.join(","),
          description: this.editor.txt.html(),
        }).then((res) => {
          console.log(this.editor.txt.html());
          if (res.data.code === 200) {
            successAlert(res.data.msg);
            //   弹窗消失
            this.cancel();
            //   清空
            this.empty();
            //   刷新列表
            this.reqgoodsList();
            // 刷新总数
            this.reqCount();
          }
        });
      });
    },

    empty() {
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: null,
        description: "",
        specsid: "",
        specsattr: [],
        isnew: 2,
        ishot: 2,
        status: 2,
      };
      // this.imgUrl = "";
      this.$refs.image.noImgUrl()
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../../less/index.less";
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed @header-color;
  position: relative;
}
.my-plus {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 100px;
  color: @parmary;
}
.my-img {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
.my-upload input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
}
</style>